package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.RoleService;
import com.itheima.UserService;
import com.itheima.contant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.RoleVo;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    @Reference
    private RoleService roleService;
    @RequestMapping("/getUserName")
    public Result getUserName(){
        try {
            /*从security的上下文对象中获取保存的用户信息*/
            User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return Result.success("",user.getUsername());
        } catch (Exception e) {
            return Result.error("");
        }
    }




    @RequestMapping("/findPage")
    public  Result findPage(@RequestBody QueryPageBean queryPageBean){
        PageResult pageResult = userService.findPage(queryPageBean);
        return Result.success("", pageResult);
    }

    @RequestMapping("/findById")
    public Result findById(@RequestParam("id") Integer id){
        com.itheima.pojo.User user  = userService.findUserById(id);
        Set<Role> roles = roleService.findAll();
        List<Integer> roleIds = userService.findRoleIdByUserId(id);
        RoleVo roleVo = new RoleVo();
        roleVo.setUser(user);
        roleVo.setRoles(roles);
        roleVo.setRoleIds(roleIds);
        return Result.success("",roleVo);
    }

    @RequestMapping("/editRole")
    public Result editRole(@RequestBody com.itheima.pojo.User user){
        try {
            userService.editRole(user);
            return Result.success("添加角色成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加角色失败");
        }
    }

    @RequestMapping("/delete")
    public Result delete(@RequestParam("id") Integer id) {
        userService.deleteById(id);
        return null;
    }


    @RequestMapping("/findByRoleId")
    public Result findUserByRoleId(@RequestParam("id") Integer id) {
        try {
            List<com.itheima.pojo.User> userList =  userService.findUserByRoleId(id);
            return Result.success("查询成功",userList);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

}
